﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using CreditAgricole.Framework;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Search.Query;
using Microsoft.Office.Server.Search.Administration;
using System.Data;

namespace CreditAgricole.PageCodeBehind
{
    public class search : ContextPage
    {
        protected Panel pnlResult;
        protected Panel pnlSummaryQuery;
        protected Panel pnlCritiriaItems;

        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable resDataTable = new DataTable();
            if (!string.IsNullOrEmpty(Request.QueryString["k"]))
            {
                SetSummaryQuery(Request.QueryString["k"], Request.QueryString["s"]);
                ResultTable queryResultsTable = SearchResultByKeyword(Request.QueryString["k"]);
                if (queryResultsTable != null)
                {
                    resDataTable.Load(queryResultsTable, LoadOption.OverwriteChanges);

                    if (resDataTable.Rows.Count > 0)
                    {
                        foreach (DataRow row in resDataTable.Rows)
                        {
                            AddResBlock(row);
                        }
                    }
                    else
                    {
                        NoResultFound();
                    }
                }
                else
                {
                    NoResultFound();
                }
            }
        }
        
        private void SetSummaryQuery(string keyword, string scope)
        {
            Label lblSummaryQuery = new Label();
            lblSummaryQuery.Text = string.Format("Mot recherché : {0} <br />", keyword);
            lblSummaryQuery.Text += string.Format("scope de recherche : {0}", scope);
            pnlSummaryQuery.Controls.Add(lblSummaryQuery);
        }

        private void NoResultFound()
        {
            Label lblNoresult = new Label();
            lblNoresult.Text = "Pas de résultat trouvé";
            pnlResult.Controls.Add(lblNoresult);
        }

        private void AddResBlock(DataRow row)
        {
            string title = MappingTool.CatchNull(row["Title"]);
            string path = MappingTool.CatchNull(row["Path"]);
            string hitHighlightedSummary = MappingTool.CatchNull(row["HitHighlightedSummary"]);
            HyperLink resLink = new HyperLink()
            {
                Text = title,
                NavigateUrl = path
            };
            Panel pnlLink = new Panel();
            pnlLink.CssClass = "res_srch_lnk";
            pnlLink.Controls.Add(resLink);

            Panel pnlSummary = new Panel();
            pnlSummary.CssClass = "res_srch_sum";
            Label lblSummary = new Label();
            lblSummary.Text = hitHighlightedSummary;
            Label lblPath = new Label();
            lblPath.Text = path;
            lblPath.CssClass = "res_srch_path";
            pnlSummary.Controls.Add(lblSummary);
            pnlSummary.Controls.Add(new LiteralControl("<br />"));
            pnlSummary.Controls.Add(new LiteralControl("<br />"));
            pnlSummary.Controls.Add(lblPath);

            Panel pnlRow = new Panel();
            pnlRow.CssClass = "res_srch_row";
            pnlRow.Controls.Add(pnlLink);
            pnlRow.Controls.Add(pnlSummary);
            pnlResult.Controls.Add(pnlRow);
        }

        private ResultTable SearchResultByKeyword(string keyword)
        {
            ResultTable queryResultsTable = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    KeywordQuery keywordQuery = new KeywordQuery(site);
                    keywordQuery.ResultTypes = ResultType.RelevantResults | ResultType.SpecialTermResults;
                    keywordQuery.EnableStemming = true;
                    keywordQuery.TrimDuplicates = true;
                    keywordQuery.IgnoreAllNoiseQuery = true;
                    if (!string.IsNullOrEmpty(Request.QueryString["s"]))
                    {
                        string selectedScope = Request.QueryString["s"];
                        keywordQuery.HiddenConstraints = "scope:" + "\"" + selectedScope + "\"";
                    }
                    keywordQuery.QueryText = keyword;

                    ResultTableCollection searchResults = keywordQuery.Execute();
                    queryResultsTable = searchResults[ResultType.RelevantResults];
                }
            });
            return queryResultsTable;
        }

    }
}
